package com.android.manghe.detail.activity

import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.Html
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import com.android.base.frame.extend.IRefresh
import com.android.base.tools.*
import com.android.base.tools.Glide.GlideHelper
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.manghe.R
import com.android.manghe.cache.ConfigHolder
import com.android.manghe.cache.UserHolder
import com.android.manghe.common.frame.activity.MVPWebSocketNoTitleActivity
import com.android.manghe.common.model.AuctionConfig
import com.android.manghe.common.model.AuctionDetailRes
import com.android.manghe.common.model.AutoJoinAuctionSocketRes
import com.android.manghe.common.model.InitAuctionRes
import com.android.manghe.detail.adapter.PeopleGotAdapter
import com.android.manghe.detail.adapter.PreviousDealAdapter
import com.android.manghe.detail.adapter.ShareOrderAdapter
import com.android.manghe.detail.model.AuctionOrderDetailRes
import com.android.manghe.detail.model.PeopleGotRes
import com.android.manghe.detail.model.PreviousDealRes
import com.android.manghe.detail.model.ShareOrderRes
import com.android.manghe.detail.precenter.PGoodDetail
import com.android.manghe.main.MainActivity
import com.android.manghe.main.view.TabEntity
import com.android.manghe.mine.activity.MyKanActivity
import com.android.manghe.view.AutoHeightGridLayoutManager
import com.android.manghe.view.AutoHeightLayoutManager
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.githang.statusbar.StatusBarCompat
import com.meiqia.meiqiasdk.util.MQIntentBuilder
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.tmall.ultraviewpager.UltraViewPager
import com.zhangke.websocket.ErrorResponse
import com.zhangke.websocket.Response
import kotlinx.android.synthetic.main.activity_good_detail.*
import kotlinx.android.synthetic.main.dialog_fail_get.*
import kotlinx.android.synthetic.main.dialog_success_get.*
import kotlinx.android.synthetic.main.layout_offer_bar.*
import kotlinx.android.synthetic.main.layout_offer_status_bar.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.roundToInt

class GoodDetailActivity : MVPWebSocketNoTitleActivity<PGoodDetail>(), IRefresh {
    private var isFromPush = false;
    private var isDeal = false
    private var langConfig: AuctionConfig.DataBean.LangBean? = null

    private var drawableCollect: Drawable? = null
    private var drawableDisCollect: Drawable? = null

    private val mTabEntities = ArrayList<CustomTabEntity>()
    private val mTitles = arrayOf("晒单分享", "往期成交", "趣砍规则")

    private var currentTimes = 5
    private var currentTimesAddMore = 5


    override fun getRefreshView(): SmartRefreshLayout {
        return findViewById(R.id.refreshLayout)
    }

    override fun onRefresh() {
        loadData()
    }

    override fun onLoad() {
        if (shareRecyclerView.visibility == View.VISIBLE) {
            p.loadShareList(false)
        }
        if (layoutPreviousDealShareListView.visibility == View.VISIBLE) {
            p.loadPreviousDealList(false)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_good_detail
    }

    override fun initData(savedInstanceState: Bundle?) {
        isFromPush = intent.getBooleanExtra("isFromPush", false)

        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, com.android.base.R.color.white))

        drawableCollect = ContextCompat.getDrawable(this, R.mipmap.collect_click)
        drawableCollect!!.setBounds(0, 0, drawableCollect!!.minimumWidth, drawableCollect!!.minimumHeight);

        drawableDisCollect = ContextCompat.getDrawable(this, R.mipmap.collect_normal)
        drawableDisCollect!!.setBounds(0, 0, drawableDisCollect!!.minimumWidth, drawableDisCollect!!.minimumHeight);

        val backIcSize = DisplayUtil.dip2px(this, 22f)
        val backIcLayoutParam = RelativeLayout.LayoutParams(backIcSize, backIcSize)
        backIcLayoutParam.topMargin = StatusBarUtil.getStatusBarHeight(this) + DisplayUtil.dip2px(this, 10f)
        backIcLayoutParam.leftMargin = DisplayUtil.dip2px(this, 14f)
        ivBack.layoutParams = backIcLayoutParam
        ivBack.setOnClickListener {
            if (isFromPush) {
                open(MainActivity::class.java)
            }
            finish()
        }
        ivBackTop.setOnClickListener {
            if (isFromPush) {
                open(MainActivity::class.java)
            }
            finish()
        }

        isDeal = intent.getBooleanExtra("isDeal", false)
        tvToNew.visibility = if (isDeal && intent.getBooleanExtra("showToNew", true)) View.VISIBLE else View.GONE

        //初始化出价记录
        gotRecyclerView.setHasFixedSize(true)
        gotRecyclerView.layoutManager = AutoHeightGridLayoutManager(this, 3)
        gotRecyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                //不是第一个的格子都设一个左边和底部的间距
                outRect.left = 16
                //由于每行都只有3个，所以第一个都是3的倍数，把左边距设为0
                if (parent.getChildLayoutPosition(view) % 3 == 0) {
                    outRect.left = 0
                }
            }
        })
        mPeopleGotAdapter = PeopleGotAdapter(this, arrayListOf())
        gotRecyclerView?.adapter = mPeopleGotAdapter

        //初始化底部三个标签内容
        for (i in mTitles.indices) {
            mTabEntities.add(TabEntity(mTitles[i], 0, 0))
        }
        tabLayout.setTabData(mTabEntities)
        tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabReselect(position: Int) {
            }

            override fun onTabSelect(position: Int) {
                showBottomTabView(position)
            }
        })
        mShareOrderAdapter = ShareOrderAdapter(arrayListOf())
        shareRecyclerView.adapter = mShareOrderAdapter
        shareRecyclerView.layoutManager = AutoHeightLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        shareRecyclerView.addItemDecoration(
            RecyclerViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL,
                1, ContextCompat.getColor(mContext, R.color.colorDivider)
            )
        )

        mPreviousDealAdapter = PreviousDealAdapter(arrayListOf())
        previousDealRecyclerView.adapter = mPreviousDealAdapter
        previousDealRecyclerView.layoutManager = AutoHeightLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        previousDealRecyclerView.addItemDecoration(
            RecyclerViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL,
                1, ContextCompat.getColor(mContext, R.color.colorDivider)
            )
        )
        mPreviousDealAdapter!!.setOnItemClickListener { adapter, _, position ->
            val intent = Intent(this@GoodDetailActivity, GoodDetailActivity::class.java)
            intent.putExtra("isDeal", true)
            intent.putExtra("orderId", (adapter.data[position] as PreviousDealRes.ListBean).id)
            intent.putExtra("showToNew", false)
            startActivity(intent)
        }

        setLangView()
        val picContainerHeight = DisplayUtil.dip2px(this, 355f)
        myScrollView.setOnScrollListener { _, y, _, _ ->
            layoutTopBar.visibility = if (y > picContainerHeight) View.VISIBLE else View.GONE
        }

        tvTip.setOnClickListener { }
        tvToNew.setOnClickListener {
            //进入新一期
            if (!TextUtils.isEmpty(p.auctionId)) {
                val intent = Intent(this@GoodDetailActivity, GoodDetailActivity::class.java)
                intent.putExtra("isDeal", false)
                intent.putExtra("orderId", p.orderId)
                intent.putExtra("auctionId", p.auctionId)
                startActivity(intent)
                finish()
            } else {
                ToastUtil.showShort(this@GoodDetailActivity, "请稍等，正在加载数据")
            }
        }
        btnDetail.setOnClickListener {
            //商品详情
            if (!TextUtils.isEmpty(p.auctionId)) {
                val intent = Intent(this@GoodDetailActivity, GoodDetailPicActivity::class.java)
                intent.putExtra("auctionId", p.auctionId)
                startActivity(intent)
            } else {
                ToastUtil.showShort(this@GoodDetailActivity, "请稍等，正在加载数据")
            }
        }
        tvAllGot.setOnClickListener {
            //出价记录
            if (!TextUtils.isEmpty(p.order_sn)) {
                val intent = Intent(this@GoodDetailActivity, PayHistoryActivity::class.java)
                intent.putExtra("order_sn", p.order_sn)
                intent.putExtra("isDeal", isDeal)
                startActivity(intent)
            } else {
                ToastUtil.showShort(this@GoodDetailActivity, "请稍等，正在加载数据")
            }
        }
        tvDataChart.setOnClickListener {
            //成交走势图
            if (!TextUtils.isEmpty(p.auctionId)) {
                open(TrendChartActivity::class.java, hashMapOf<String, Any>("auctionId" to p.auctionId))
            } else {
                ToastUtil.showShort(this@GoodDetailActivity, "请稍等，正在加载数据")
            }
        }
        tvCollect.setOnClickListener {
            p.changeCollectStatus()
        }
        tvCollectAddMore.setOnClickListener {
            p.changeCollectStatus()
        }
        tvService.setOnClickListener {
            val userInfo = UserHolder.getUserInfo(this@GoodDetailActivity)
            userInfo?.let {
                val clientInfo = HashMap<String, String>();
                clientInfo.put("mid", it.UID);
                clientInfo.put("nickName", it.nickname);
                clientInfo.put("avatar", it.avatar);
                startActivity(
                    MQIntentBuilder(this@GoodDetailActivity)
                        .setClientInfo(clientInfo) // 设置顾客信息 PS: 这个接口只会生效一次,如果需要更新顾客信息,需要调用更新接口
                        .build()
                );
            }


//            WebViewActivity.showActivity(
//                mContext, WebViewParameter.WebParameterBuilder()
//                    .setUrl(ConstantsUrl.host + ConstantsUrl.CHAT_WEB)
//                    .setShowProgress(true)
//                    .setCanHistoryGoBackOrForward(true)
//                    .setReloadable(true)
//                    .setReloadType(ERefreshWebType.ClickRefresh)
//                    .setCustomTitle("客服")
//                    .build()
//            )
        }
        tvServiceAddMore.setOnClickListener {
            //            WebViewActivity.showActivity(
//                mContext, WebViewParameter.WebParameterBuilder()
//                    .setUrl(ConstantsUrl.host + ConstantsUrl.CHAT_WEB)
//                    .setShowProgress(true)
//                    .setCanHistoryGoBackOrForward(true)
//                    .setReloadable(true)
//                    .setReloadType(ERefreshWebType.ClickRefresh)
//                    .setCustomTitle("客服")
//                    .build()
//            )
            val userInfo = UserHolder.getUserInfo(this@GoodDetailActivity)
            userInfo?.let {
                val clientInfo = HashMap<String, String>();
                clientInfo.put("mid", it.UID);
                clientInfo.put("nickName", it.nickname);
                clientInfo.put("avatar", it.avatar);
                startActivity(
                    MQIntentBuilder(this@GoodDetailActivity)
                        .setClientInfo(clientInfo) // 设置顾客信息 PS: 这个接口只会生效一次,如果需要更新顾客信息,需要调用更新接口
                        .build()
                );
            }
        }

        // 出价次数输入监听
        offerPop.setParam(offerTimes.text.toString()) { times ->
            offerTimes.setText(times.toString() + "")
        }
        offerTimesAddMore.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                var currentText = offerTimesAddMore.text.toString()
                if (TextUtils.isEmpty(currentText)) {
                    currentText = "1"
                    offerTimesAddMore.setText(currentText)
                } else if (Integer.parseInt(currentText) < 1) {
                    currentText = "1"
                    offerTimesAddMore.setText(currentText)
                }
                currentTimesAddMore = Integer.parseInt(currentText)
            }

            override fun afterTextChanged(s: Editable) {

            }
        })
        offerTimes.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                var currentText = offerTimes.text.toString()
                if (TextUtils.isEmpty(currentText)) {
                    currentText = "1"
                    offerTimes.setText(currentText)
                } else if (Integer.parseInt(currentText) < 1) {
                    currentText = "1"
                    offerTimes.setText(currentText)
                }
                if (offerPop != null) {
                    offerPop.setTimes(currentText)
                }
                currentTimes = Integer.parseInt(currentText)
            }

            override fun afterTextChanged(s: Editable) {

            }
        })
        reduce.setOnClickListener {
            if (currentTimes > 1) {
                currentTimes--
                offerTimes.setText(currentTimes.toString() + "")
            }
        }
        add.setOnClickListener {
            if (currentTimes >= 1) {
                currentTimes++
                offerTimes.setText(currentTimes.toString() + "")
            }
        }
        reduceAddMore.setOnClickListener {
            if (currentTimesAddMore > 1) {
                currentTimesAddMore--
                offerTimesAddMore.setText(currentTimesAddMore.toString() + "")
            }
        }
        addAddMore.setOnClickListener {
            if (currentTimesAddMore >= 1) {
                currentTimesAddMore++
                offerTimesAddMore.setText(currentTimesAddMore.toString() + "")
            }
        }
        offerTimes.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {//获得焦点
                showOfferPopup()
            }
        }
        offerTimes.setOnClickListener {
            showOfferPopup()
        }
        toOffer.setOnClickListener {
            //出价
            KeyboardUtil.hideInputMethodWindow(this, offerTimes)
            closeOfferPopup()

            val userInfo = UserHolder.getUserInfo(this)
            mPeopleGotAdapter?.let {
                if (it.itemCount != 0 && userInfo != null &&
                    it.getItem(0).mid == userInfo.UID
                ) {
                    ToastUtil.showShort(this, "您已领先 无需重复出价")
                    return@setOnClickListener
                }
            }


            if (currentTimes == 1) {
                p.toOfferOneTime()
            } else {
                p.toOffer(currentTimes, false)
            }

        }
        tvAddMore.setOnClickListener {
            //追加出价
            KeyboardUtil.hideInputMethodWindow(this, offerTimes)
            p.toOffer(currentTimesAddMore, true)
        }
        layoutOfferStatusBar.setOnClickListener { }
        handler.postDelayed(mRunnable, 40)
        loadData()
    }

    fun setLangView() {
        try {
            val config = ConfigHolder.getConfigInfo(this)
            if (config != null) {
                langConfig = config.lang
                if (langConfig != null) {
                    layoutBackPercent.visibility = View.VISIBLE
                    tvBackPercentTitle.text = langConfig!!.return_times_rate_key
                    tvBackPercent.text = langConfig!!.return_times_rate_value
                } else {
                    layoutBackPercent.visibility = View.GONE
                }
                if (!TextUtils.isEmpty(config.auction_rule)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        tvRule.text = Html.fromHtml(config.auction_rule, Html.FROM_HTML_MODE_COMPACT)
                    }else{
                        tvRule.text = Html.fromHtml(config.auction_rule)
                    }
                }
            } else {
                //获取配置
                p.loadConfig()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private var showPopTimer: Timer? = null

    private fun showOfferPopup() {
        offerPop.show()
        if (showPopTimer != null) {
            showPopTimer!!.cancel()
            showPopTimer = null
        }
        showPopTimer = Timer()
        showPopTimer!!.schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread { closeOfferPopup() }
            }
        }, 3000)
    }

    private fun closeOfferPopup() {
        if (offerPop != null) {
            offerPop.dismiss()
            if (showPopTimer != null) {
                showPopTimer!!.cancel()
            }
        }
    }

    private fun showBottomTabView(position: Int) {
        when (position) {
            0 -> {
                layoutShareListView.visibility = View.VISIBLE
                layoutPreviousDealShareListView.visibility = View.GONE
                tvRule.visibility = View.GONE
            }
            1 -> {
                layoutShareListView.visibility = View.GONE
                layoutPreviousDealShareListView.visibility = View.VISIBLE
                tvRule.visibility = View.GONE
            }
            2 -> {
                layoutShareListView.visibility = View.GONE
                layoutPreviousDealShareListView.visibility = View.GONE
                tvRule.visibility = View.VISIBLE
            }
        }
    }

    fun setCollectStatus(isCollect: Boolean) {
        tvCollect.setCompoundDrawables(null, if (isCollect) drawableCollect else drawableDisCollect, null, null)
    }

    private fun loadData() {
        p.setOrderId(intent.getStringExtra("orderId"))
        p.setAuctionId(intent.getStringExtra("auctionId"))
        if (isDeal) {
            //已经成交了的
            p.loadData()
        } else {
            p.getCollectStatus()
            p.loadDetailBySocket()
        }
    }

    override fun onMessageResponse(message: Response<*>?) {
        message?.let {
            if (!isDeal && it.responseText.isNotEmpty()) {
                p.dealSocketData(it.responseText)
            }
        }
    }

    override fun onSendMessageError(error: ErrorResponse?) {
    }

    fun updateView(detail: AuctionOrderDetailRes.DataBean) {
        //图片
        detail.thumbs?.let {
            ultraViewPager.adapter = GoodThumbViewPager(this, it)
            if (it.size > 1) {
                ultraViewPager.initIndicator()
                    .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                    .setFocusColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                    .setNormalColor(ContextCompat.getColor(mContext, R.color.backgroundGray))
                    .setRadius(DisplayUtil.dip2px(mContext, 6f)).setMargin(0, 0, 0, DisplayUtil.dip2px(mContext, 10f))
                    .setGravity(Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM)
                    .build()
                ultraViewPager.setInfiniteLoop(true)
                ultraViewPager.setAutoScroll(5000)
            } else {
                ultraViewPager.disableIndicator()
                ultraViewPager.setInfiniteLoop(false)
            }
        }
        //价格
        tvPrice.text = "￥${BigDecimalUtils.round(detail.price, 2)}"
        tvPriceTop.text = "￥${BigDecimalUtils.round(detail.price, 2)}"
        tvMarketPrice.text = "￥${detail.market_price}"
        tvMarketPriceTop.text = "￥${detail.market_price}"
        tvMarketPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
        tvMarketPriceTop.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG

        //title
        tvTitle.text = detail.title

        //我使用的砍币
        tvOutCoin.text = BigDecimalUtils.mul(detail.mid_coin_count.toString(), detail.brokerage.toString(), 0)

        //规则数据
        tvStartPrice.text = "￥${detail.start_price}"
        tvAddSpacePrice.text = "￥${detail.per_price}"
        tvNetworkServicePrice.text = "${detail.brokerage}砍币"
        tvCountDownSecond.text = "${detail.first_countdown}秒"
    }

    private var residueMin = 0
    private var residueSecond = 0
    private var isSetThumbsOk = false;
    fun updateViewBySocket(detail: AuctionDetailRes.AuctionBean) {
        detail.thumbs?.let {
            if (!isSetThumbsOk) {
                isSetThumbsOk = true
                ultraViewPager.adapter = GoodThumbViewPager(this, it.toTypedArray())
                if (it.size > 1) {
                    ultraViewPager.initIndicator()
                        .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                        .setFocusColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                        .setNormalColor(ContextCompat.getColor(mContext, R.color.backgroundGray))
                        .setRadius(DisplayUtil.dip2px(mContext, 6f))
                        .setMargin(0, 0, 0, DisplayUtil.dip2px(mContext, 10f))
                        .setGravity(Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM)
                        .build()
                    ultraViewPager.setInfiniteLoop(true)
                    ultraViewPager.setAutoScroll(5000)
                } else {
                    ultraViewPager.disableIndicator()
                    ultraViewPager.setInfiniteLoop(false)
                }
            }
        }

        //倒计时
        if (detail.start > 0) {
            //还没开始
            tvTip.visibility = View.VISIBLE
            tvCountTip.text = "距离开始还有"
            tvCountTipTop.text = "距离开始还有"
            layoutOfferBar.visibility = View.VISIBLE
            layoutOfferStatusBar.visibility = View.GONE
            tvReduceAutoZERO.visibility = View.GONE
            tvReduceAutoZEROTop.visibility = View.GONE
            tvReduceAuto.visibility = View.VISIBLE
            tvReduceAutoTop.visibility = View.VISIBLE
            residueMin = detail.time / 60
            residueSecond = detail.time % 60
            tvMinute.text = (if (residueMin < 10) "0$residueMin" else residueMin).toString()
            tvMinuteTop.text = (if (residueMin < 10) "0$residueMin" else residueMin).toString()
            tvSecond.text = (if (residueSecond < 10) "0$residueSecond" else residueSecond).toString()
            tvSecondTop.text = (if (residueSecond < 10) "0$residueSecond" else residueSecond).toString()
        } else {
            //已开始
            tvTip.visibility = View.GONE
            if (detail.time > 0) {
                tvCountTip.text = "距离结束仅剩"
                tvCountTipTop.text = "距离结束仅剩"
                residueMin = detail.time / 60
                residueSecond = detail.time % 60
                tvMinute.text = (if (residueMin < 10) "0$residueMin" else residueMin).toString()
                tvMinuteTop.text = (if (residueMin < 10) "0$residueMin" else residueMin).toString()
                tvSecond.text = (if (residueSecond < 10) "0$residueSecond" else residueSecond).toString()
                tvSecondTop.text = (if (residueSecond < 10) "0$residueSecond" else residueSecond).toString()
                tvReduceAutoZERO.visibility = View.GONE
                tvReduceAutoZEROTop.visibility = View.GONE
                tvReduceAuto.visibility = View.VISIBLE
                tvReduceAutoTop.visibility = View.VISIBLE
            } else {
                tvMinute.text = "00"
                tvMinuteTop.text = "00"
                tvSecond.text = "00"
                tvSecondTop.text = "00"
                tvReduceAuto.text = "00"
                tvReduceAutoTop.text = "00"
                tvReduceAutoZERO.visibility = View.VISIBLE
                tvReduceAutoZEROTop.visibility = View.VISIBLE
                tvReduceAuto.visibility = View.GONE
                tvReduceAutoTop.visibility = View.GONE
                tvCountTip.text = "已结束"
                tvCountTipTop.text = "已结束"
            }
            layoutOfferBar.visibility = View.VISIBLE
        }

        //价格
        tvPrice.text = "￥${BigDecimalUtils.round(detail.price, 2)}"
        tvPriceTop.text = "￥${BigDecimalUtils.round(detail.price, 2)}"
        tvMarketPrice.text = "￥${detail.market_price}"
        tvMarketPriceTop.text = "￥${detail.market_price}"
        tvMarketPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
        tvMarketPriceTop.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG

        //title
        tvTitle.text = detail.title

        //我使用的砍币
        tvOutCoin.text = BigDecimalUtils.mul(detail.mid_count.toString(), detail.brokerage.toString(), 0)

        //规则数据
        tvStartPrice.text = "￥${detail.start_price}"
        tvAddSpacePrice.text = "￥${detail.per_price}"
        tvNetworkServicePrice.text = "${detail.brokerage}砍币"
        tvCountDownSecond.text = "${detail.first_countdown}秒"
    }

    private var message: Message? = null
    private val mRunnable = object : Runnable {

        override fun run() {
            if (null == message) {
                message = Message()
            } else {
                message = Message.obtain()
            }
            message!!.what = 0
            //发送信息给handler
            handler.sendMessage(message)
            //每40豪秒重启一下线程
            handler.postDelayed(this, 40)
        }
    }
    private var countDownAuto = 0;
    private val handler = object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            countDownAuto = (Math.random() * 60).roundToInt()
            tvReduceAuto.text = if (countDownAuto < 10) "0$countDownAuto" else countDownAuto.toString()
            tvReduceAutoTop.text = if (countDownAuto < 10) "0$countDownAuto" else countDownAuto.toString()
        }
    }


    fun updateCollectionView(initAuction: InitAuctionRes) {
        tvWeiGuan.text = "围观:${initAuction.watch_num}人"
        tvChuJia.text = "出价:${initAuction.bid_num}人"
        tvCollected.text = "收藏:${initAuction.favorite_num}人"
    }

    fun updateAutoOfferView(autoJoinAuctionResultData: AutoJoinAuctionSocketRes) {
        if (!TextUtils.isEmpty(autoJoinAuctionResultData.type)) {
            //更新自动出价次数进度条
            val total = autoJoinAuctionResultData.count
            val current = autoJoinAuctionResultData.checkout
//            have_consumered_money.setText(autoJoinAuctionResultData.mid_count.toString() + "")
            offeredProgress.max = total
            offeredProgress.progress = current
            tvOfferedTimes.text = "次数剩余" + (total - current) + "次"

            if (autoJoinAuctionResultData.checkout !== autoJoinAuctionResultData.count) {
                layoutOfferBar.visibility = View.GONE
                layoutOfferStatusBar.visibility = View.VISIBLE
//                p.getAutoJoinAuction()
            } else {
                Handler().postDelayed({
                    layoutOfferBar.visibility = View.VISIBLE
                    layoutOfferStatusBar.visibility = View.GONE
                    currentTimes = Integer.parseInt(offerTimes.text.toString().trim { it <= ' ' })
                }, 2000)
            }


        }
    }

    fun setNotice(noticeText: String) {
        //设置消息
        tvNotice.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            Html.fromHtml(noticeText, Html.FROM_HTML_MODE_COMPACT) else Html.fromHtml(noticeText)
    }

    //---------------------设置出价记录
    private var mPeopleGotAdapter: PeopleGotAdapter? = null

    fun updateChuJia(gotList: List<PeopleGotRes.ListBean>) {
        mPeopleGotAdapter?.let {
            if (gotList != null && gotList.isNotEmpty()) {
                gotList[0].isTop = true
                peopleGotEmptyView.visibility = View.GONE
            } else {
                peopleGotEmptyView.visibility = View.VISIBLE
            }
            it.update(gotList)
        }
    }

    //---------------------设置分享晒单
    private var mShareOrderAdapter: ShareOrderAdapter? = null

    fun updateShareOrder(shareList: List<ShareOrderRes.ListBean>) {
        mShareOrderAdapter?.let {
            it.replaceData(shareList)
        }
    }


    //---------------------设置往期成交
    private var mPreviousDealAdapter: PreviousDealAdapter? = null

    fun updatePreviousDeal(dealList: List<PreviousDealRes.ListBean>) {
        mPreviousDealAdapter?.let {
            it.replaceData(dealList)
        }
    }

    fun toNexRound() {
        //下一期弹框
        p.quitAuction()
        tvTip.visibility = View.VISIBLE
        tvTip.setBackgroundResource(R.color.grey500)

        if (handler != null) {
            handler.removeCallbacks(mRunnable)
        }
        tvReduceAutoZERO.visibility = View.VISIBLE
        tvReduceAutoZEROTop.visibility = View.VISIBLE
        tvReduceAuto.visibility = View.GONE
        tvReduceAutoTop.visibility = View.GONE
        tvToNew.visibility = View.GONE
        layoutOfferBar.visibility = View.GONE
        layoutOfferStatusBar.visibility = View.GONE

        layoutFailDialog.visibility = View.VISIBLE
        layoutFailDialog.setOnClickListener { }
        tvBtnDialog.setOnClickListener {
            //进入下一期
            val intent = Intent(this@GoodDetailActivity, GoodDetailActivity::class.java)
            intent.putExtra("auctionId", p.auctionId)
            startActivity(intent)
            finish()
        }

    }

    fun gameOver() {
        tvReduceAutoZERO.visibility = View.VISIBLE
        tvReduceAutoZEROTop.visibility = View.VISIBLE

        p.quitAuction()
        if (handler != null) {
            handler.removeCallbacks(mRunnable)
        }
        tvReduceAuto.visibility = View.GONE
        tvReduceAutoTop.visibility = View.GONE
        tvToNew.visibility = View.VISIBLE
        tvTip.visibility = View.GONE
        layoutOfferBar.visibility = View.GONE
        layoutOfferStatusBar.visibility = View.GONE

//        layoutFailDialog.visibility = View.VISIBLE
//        tvToNexTip.visibility = View.GONE
//        layoutFailDialog.setOnClickListener { }
//        tvBtnDialog.setOnClickListener {
//            //退出界面
//            finish()
//        }

    }

    fun showWinDialog(price: String) {
        //成功拍到提示框
        layoutSuccessDialog.visibility = View.VISIBLE
        tvPriceSuccessDialog.text = "成交价：${price}元"
        layoutSuccessDialog.setOnClickListener { }
        tvToGetSuccessDialog.setOnClickListener {
            finish()
            open(MyKanActivity::class.java)
        }
    }

    override fun onDestroy() {
        if (!isDeal) {
            p.quitAuction()
            p.stopSocketTimer()
            handler.removeCallbacks(mRunnable)
        }
        super.onDestroy()
    }
}

class GoodThumbViewPager(context: Context, thumbList: Array<String>) : PagerAdapter() {

    private var thumbList: Array<String>? = null
    private var context: Context? = null

    init {
        this.context = context
        this.thumbList = thumbList
    }

    override fun getCount(): Int {
        return thumbList!!.size
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view === `object`
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val imageView = LayoutInflater.from(container.context).inflate(R.layout.layout_pager_iv_item, null) as ImageView
        imageView.scaleType = ImageView.ScaleType.FIT_CENTER
        GlideHelper.load(context, thumbList!![position], imageView)
        container.addView(imageView)
        imageView.setOnClickListener {

        }
        return imageView
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        val view = `object` as ImageView
        container.removeView(view)
    }

}